package com.chungkui.demo.mvc;

import com.chungkui.check.core.Constants;
import com.chungkui.check.core.bean.CheckResult;
import com.chungkui.check.expression.BaseExpression;
import com.chungkui.check.handler.insidecheck.InsideType;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author: jason
 * @Date: 2020/5/22 14:33
 * @Version 1.0
 */
public class PhoneMatchExpression extends BaseExpression {
    private String param;
    private String code;
    private Boolean require;
    private static Pattern pattern = Pattern.compile("^1(3|4|5|7|8)\\d{9}$");
    private Map<String, Object> msg;

    @Override
    public CheckResult match(Map<String, Object> params) {
        String v = MapUtils.getString(params, this.param);
        if (require != null && require && StringUtils.isEmpty(v)) {
            return CheckResult.fail(this.code,MapUtils.getString(this.msg, Constants.NULL));
        }
        if (StringUtils.isNotEmpty(v)) {
            Matcher m = pattern.matcher(v);
            boolean isMatch = m.matches();
            if (!isMatch) {
                return CheckResult.fail(this.code,MapUtils.getString(this.msg, "error"));
            }
        }
        return CheckResult.success();
    }

    @Override
    public void compile(Map<String, Object> config) {
        this.param = MapUtils.getString(config, "param");
        this.code = MapUtils.getString(config, "code");
        this.msg = (Map<String, Object>) MapUtils.getMap(config,  Constants.MSG);
        this.require = MapUtils.getBoolean(config, "require");
    }

    @Override
    public InsideType getInsideType() {
        return null;
    }
}
